
/**
 * imagecache.h
 * 
 * ImageCache is the cache of profile image
 * 
 * Copyright (c) 2008 Harunobu Oyama <nobukichi at gmail.com>
 * Licensed under GNU GPL version 3
 *
 */

#ifndef		IMAGE_CACHE_INCLUDED
#define		IMAGE_CACHE_INCLUDED

#include <boost/shared_ptr.hpp>
#include <QObject>
#include <QBuffer>
#include <QString>
#include <QIcon>
#include <QHttp>

class ImageCache : public QObject
{
	Q_OBJECT

public:
	static ImageCache* getInstance();

	//! we should take the icon from url as it can change over the time,
	//! however, we do not have the url while we cache the local post,
	//! in that case, we use the icon for the user most recently used.
	QIcon icon(const QString& user, const QString& url = "");

	//! reset all the request before exiting.
	void reset();

	~ImageCache();

signals:
	//! this signal is emitted when an image file is downloaded
	void signalImageDownloaded();

private:
	//! ImageCache request object
	class Request {
	public:
		explicit Request(const QString& url = "");
		QBuffer* responseBuffer();
		QString url() const;
	private:
		QString imageUrl;
		boost::shared_ptr<QBuffer> ptrResponseBuffer;
	};
	
	//! this is a singleton class
	ImageCache(QObject* parent = 0);

	QHttp http; //! http engine used to download images

	static ImageCache* theInstance;

	//! map from url to icon
	typedef std::map<QString, QIcon> MapUrlToIcon;
	MapUrlToIcon urlToIcon;

	typedef std::map<QString, QString> MapUserNameToUrl;
	MapUserNameToUrl userToUrl;

	typedef std::map<int, Request> RequestMap;
	RequestMap activeRequests; //! map from request id returned by QHttp to Request object holding a QBuffer to receive the http response

	//! default icon to be shown while the icon is being downloaded
	QIcon defaultIcon;

	void sendGetIconRequest(const QString& url);

private slots:
	//! slot to receive http response from QHttp
	void slotRequestFinished(int id, bool error);
};

#endif	//	IMAGE_CACHE_INCLUDED

